from flask import (
    Blueprint,
    request,
    g,
    render_template,
)

from exit import db
from .decorators import login_need
from flask_paginate import Pagination, get_page_parameter
from apps.mall.models import *
from .models import CMSRecord
from .forms import *
from apps.mall.forms import DetailForm
from apps.common.models import *
from utils import restful, common_util, api_util
from datetime import datetime
from apps.api.models import *
from apps.mall.models_v2 import *
import requests
import json
from .views_cms import bp
from sqlalchemy import or_
import ast
from decimal import Decimal


@bp.route('/mall/mall_orders/')  # 后台订单页面
@login_need
def mall_orders():

    status = request.args.get('status')
    # print(status, '1111111111')
    user_id = request.args.get('user_id')
    t_type = request.args.get('t_type')
    delivery = Delivery.query.all()
    if status == '0':
        return render_template('cms_mall/mall_send_orders.html', delivery=delivery, status=0, user_id=user_id, t_type=t_type)
    elif status == '1':
        return render_template('cms_mall/mall_all_orders.html', delivery=delivery, status=1, user_id=user_id)
    # elif status == '2':
    #     return render_template('cms_mall/mall_confirm_orders.html', delivery=delivery, status=status, user_id=user_id)
    elif status == '3':
        return render_template('cms_mall/mall_all_orders.html', delivery=delivery, status=1, user_id=user_id)
    else:
        return render_template('cms_mall/mall_all_orders.html', delivery=delivery, status=status, user_id=user_id)


@bp.route('/mall/mall_orders_detail/')   # 订单详情
@login_need
def mall_orders_detail():
    order_id = request.args.get('order_id')
    # print(order_id)
    buy_order = BuyOrder.query.filter_by(id=order_id).first()
    buy_order_info = {
        'order_id': order_id
    }
    if buy_order:
        buy_order_info = buy_order.buy_order_json()
        user = User.query.filter_by(id=buy_order.user_id).first()
        buy_order_info['phone'] = user.phone
        buy_order_info['username'] = user.username

        # 收货地址
        # user_address = UserAddress.query.filter_by(id=buy_order.address_id, user_id=buy_order.user_id).first()
        # if user_address:
        #     buy_order_info['name'] = user_address.name
        #     buy_order_info['address_phone'] = user_address.phone
        #     buy_order_info['province'] = user_address.province
        #     buy_order_info['city'] = user_address.city
        #     buy_order_info['district'] = user_address.district
        #     buy_order_info['place'] = user_address.place
    return render_template('cms_mall/mall_detail_orders.html', **buy_order_info)


@bp.route('/mall/orders_detail_info/')  # 订单详情信息
@login_need
def orders_detail_info():
    order_id = request.args.get('order_id')
    buy_order = BuyOrder.query.filter_by(id=order_id).first()
    order_goods = BuyOrderGoods.query.filter_by(order_id=buy_order.id).all()
    goods_list = list()
    for i in order_goods:
        buy_goods_info = i.buy_goods_json()

        buy_goods_info['status_str'] = api_util.order_goods_status_str(i.status)
        buy_goods_info['back_status_str'] = api_util.order_goods_back_status_str(i.back_status)
        goods_list.append(buy_goods_info)
    return restful.table_success(data=goods_list, count=len(order_goods))


@bp.route('/mall/mall_orders_info/')  # 商城订单信息
@login_need
def mall_orders_info():
    page = request.args.get(get_page_parameter(), type=int, default=1)
    limit = request.args.get('limit', type=int, default=10)
    start = (page - 1) * int(limit)
    end = start + int(limit)
    shipping_order_list = list()
    user_id = request.args.get('user_id')
    status = request.args.get('status')
    status = int(status)
    # print(status, '======')
    if status <= 2:
        if status == 0:
            if user_id:
                buy_obj = db.session.query(BuyOrder).join(User, BuyOrder.user_id == User.id).filter(
                    User.phone == user_id,
                    BuyOrder.status == status,
                ).order_by(BuyOrder.create_time)
            else:
                buy_obj = BuyOrder.query.filter(
                    BuyOrder.status == status,
                ).order_by(BuyOrder.create_time)
        else:
            if user_id:
                buy_obj = db.session.query(BuyOrder).join(User, BuyOrder.user_id == User.id).filter(
                    User.phone == user_id,
                    BuyOrder.status == status,
                ).order_by(BuyOrder.create_time)
            else:
                # print('===========')
                buy_obj = BuyOrder.query.filter(
                    BuyOrder.status == status,
                ).order_by(BuyOrder.create_time)
    else:
        if user_id:
            buy_obj = db.session.query(BuyOrder).join(User, BuyOrder.user_id == User.id).filter(
                User.phone == user_id,
                or_(BuyOrder.status == 2, BuyOrder.status == 3, BuyOrder.status == 4),
            )
        else:
            buy_obj = BuyOrder.query.filter(
                or_(BuyOrder.status == 2, BuyOrder.status == 3, BuyOrder.status == 4),
            )

    total = buy_obj.count()
    shipping_order = buy_obj.slice(start, end)
    for i in shipping_order:
        shipping_order_json = i.buy_order_json()
        user = User.query.filter_by(id=i.user_id).first()

        shipping_order_json['order_id'] = i.id
        shipping_order_json['phone'] = user.phone
        shipping_order_json['user_id'] = user.id
        shipping_order_json['username'] = user.username
        shipping_order_json['nickname'] = user.nickname
        shipping_order_json['status'] = api_util.order_status_to_str(i.status)
        # shipping_order_json['pay_type'] = api_util.pay_type_to_str(str(i.pay_type))
        goods = Goods.query.filter_by(id=i.goods_id).first()
        if goods:
            shipping_order_json['goods_name'] = goods.name

        shipping_order_list.append(shipping_order_json)
    return restful.table_success(data=shipping_order_list, count=total)


@bp.route('/mall/buy_deal_deliver_info/')    # 发货订单信息
@login_need
def buy_deal_deliver_info():
    page = request.args.get(get_page_parameter(), type=int, default=1)
    limit = request.args.get('limit', type=int, default=10)
    start = (page - 1) * int(limit)
    end = start + int(limit)
    shipping_order_list = list()
    user_id = request.args.get('user_id')
    status = request.args.get('status')
    t_type = request.args.get('t_type', type=int, default=0)
    status = int(status)
    print(t_type)

    if user_id:
        buy_obj = db.session.query(BuyDealDeliver).join(User, BuyDealDeliver.user_id == User.id).filter(
            User.phone == user_id,
            BuyDealDeliver.status == status,
            BuyDealDeliver.t_type == t_type,
        ).order_by(BuyDealDeliver.create_time)
    else:
        buy_obj = BuyDealDeliver.query.filter(
            BuyDealDeliver.status == status,
            BuyDealDeliver.t_type == t_type,
        ).order_by(BuyDealDeliver.create_time)

    total = buy_obj.count()
    shipping_order = buy_obj.slice(start, end)
    for i in shipping_order:
        shipping_order_json = i.buy_deal_deliver_json()
        user = User.query.filter_by(id=i.user_id).first()

        shipping_order_json['update_time'] = i.update_time.strftime('%Y-%m-%d %H:%M:%S') if i.update_time else ''
        shipping_order_json['order_id'] = i.id
        shipping_order_json['phone'] = user.phone
        shipping_order_json['user_id'] = user.id
        shipping_order_json['username'] = user.username
        shipping_order_json['nickname'] = user.nickname
        # shipping_order_json['status'] = api_util.order_status_to_str(i.status)
        goods = Goods.query.filter_by(id=i.goods_id).first()
        if goods:
            shipping_order_json['goods_name'] = goods.name

        shipping_order_list.append(shipping_order_json)
    return restful.table_success(data=shipping_order_list, count=total)


@bp.route('/mall/shipping_success_button/', methods=['POST'])   # 购买发货完成
@login_need
def shipping_success_button():
    order_id = request.form.get('order_id')
    logistics_num = request.form.get('logistics_num')
    delivery_id = request.form.get('data_id')
    # print(order_id)
    buy_order = BuyDealDeliver.query.filter_by(id=order_id, status=0).first()
    if not buy_order:
        return restful.params_error(message='未找到订单, 或订单已改变状态!')
    if logistics_num is None:
        return restful.params_error(message='请输入快递信息')
    delivery = Delivery.query.filter_by(id=delivery_id).first()
    if delivery is None:
        return restful.params_error(message='未找到快递公司')
    user = User.query.filter_by(id=buy_order.user_id).first()
    if user is None:
        return restful.params_error(message='未找到用户')
    now = datetime.now()
    buy_order.update_time = now
    buy_order.logistics_num = logistics_num
    # buy_order.logistics_name = delivery_id
    buy_order.logistics_name = delivery.name
    buy_order.logistics_simple = delivery.simple
    buy_order.status = 1

    record = '提货订单<{}>发货'.format(buy_order.logistics_num)
    # 后台记录
    cms_record = CMSRecord(
        cms_id=g.cms_user.id,
        ip=request.remote_addr,
        record=record,
        user_id=user.id,
    )
    db.session.add(cms_record)
    db.session.commit()
    return restful.success()


@bp.route('/mall/deal_manage/')      # 交易订单
@login_need
def deal_manage():
    user_id = request.args.get('user_id')
    status = request.args.get('status')
    start_time = request.args.get('start_time')
    end_time = request.args.get('end_time')
    print(status)
    return render_template('cms_mall/orders_deal.html', user_id=user_id, status=status, start_time=start_time, end_time=end_time)


@bp.route('/mall/deal_info/')
@login_need
def deal_info():
    page = request.args.get(get_page_parameter(), type=int, default=1)
    limit = request.args.get('limit', type=int, default=10)
    start = (page - 1) * int(limit)
    end = start + int(limit)
    user_id = request.args.get('user_id')
    status = request.args.get('status')
    start_time = request.args.get('start_time')
    end_time = request.args.get('end_time')

    if status:
        status = int(status)
    deal_list = list()
    filters = list()

    if start_time:
        filters.append(BuyDeal.create_time >= start_time)
    if end_time:
        filters.append(BuyDeal.create_time < end_time)
    if user_id:
        filters.append(User.phone == user_id)

    # if status == 1:
    #
    #     deal_obj = db.session.query(BuyDeal).join(
    #         User, BuyDeal.buyer_id == User.id
    #     ).filter(User.phone == user_id)
    # elif status == 2:
    #     deal_obj = db.session.query(BuyDeal).join(
    #         User, BuyDeal.buyer_id == User.id
    #     ).filter(User.phone == user_id)
    # else:
    if status == 2:
        deal_obj = db.session.query(BuyDeal).join(
            User, BuyDeal.seller_id == User.id
        ).filter(*filters)
    else:
        deal_obj = db.session.query(BuyDeal).join(
                 User, BuyDeal.buyer_id == User.id
             ).filter(*filters)

    buy_deal = deal_obj.order_by(BuyDeal.create_time.desc()).slice(start, end)
    for i in buy_deal:
        info = i.buy_deal_json()
        info['deal_id'] = i.id
        info['buy_fee'] = i.buy_fee
        buyer = User.query.filter_by(id=i.buyer_id).first()
        seller = User.query.filter_by(id=i.seller_id).first()
        info['buy_phone'] = '无'
        info['buy_username'] = '无'
        if buyer:
            info['buy_phone'] = buyer.phone
            info['buy_username'] = buyer.username
        info['sell_phone'] = '无'
        info['sell_username'] = '无'
        if seller:
            info['sell_phone'] = seller.phone
            info['sell_username'] = seller.username
        info['deal_type_status'] = '系统分配'
        if i.deal_type == 2:
            info['deal_type_status'] = '点对点'
        elif i.deal_type == 3:
            info['deal_type_status'] = '协议转让'
        deal_list.append(info)

    total = deal_obj.count()

    return restful.table_success(data=deal_list, count=total)


